package main

import (
	"bufio"
	"errors"
	"io"
	"os/exec"
)

func ExecShel(shell string) error {
	cmd := exec.Command("bash", "-c", shell)
	logger.Println("执行脚本:", shell)
	stdoutPipe, err := cmd.StdoutPipe()
	if err != nil {
		return errors.New("error creating StdoutPipe for Cmd: " + err.Error())
	}
	go printPipeLine(stdoutPipe)
	stderrPipe, err := cmd.StderrPipe()
	if err != nil {
		return errors.New("error creating StderrPipe for Cmd: " + err.Error())
	}
	go printPipeLine(stderrPipe)
	err = cmd.Start()
	if err != nil {
		return errors.New("脚本执行错误: " + err.Error())
	}
	err = cmd.Wait()
	if err != nil {
		return errors.New("脚本执行错误: " + err.Error())
	}
	return nil
}

func printPipeLine(pipe io.ReadCloser) {
	func() {
		scanner := bufio.NewScanner(pipe)
		for scanner.Scan() {
			logger.Println(scanner.Text())
		}
		if err := scanner.Err(); err != nil {
			logger.Println("流读取异常: ", err)
		}
	}()
}
